
from PythonCard import model 
from Brain.world import ATTRIBUTES
from Brain.condition import Condition

choices = ATTRIBUTES[:] + ['alwaystrue',]
choices.sort()

class ConditionDialog(model.CustomDialog):
	
	def __init__(self, parent, condition):
		model.CustomDialog.__init__(self, parent)
		self._result_ = None
		self.components.first_operand.items = choices
		self.components.second_operand.items = choices
		if condition:
			self.components.first_operand.text = str(condition._first.value)
			self.components.second_operand.text = str(condition._second.value)
			self.components.operator_.stringSelection = str(condition._operator)

	def process(self):
		""" return Condition from user input
		"""
		ret = Condition()
		first = self.components.first_operand.text
		second = self.components.second_operand.text
		op = self.components.operator_.stringSelection
		self.assign_operand(ret._first, first)
		self.assign_operand(ret._second, second)
		ret._operator = op
		return ret
	
	def assign_operand(self, operand, value):
		if value in ATTRIBUTES:
			operand.type = 'worldattribute'
			operand.value = value
		elif value == 'alwaystrue':
			operand.type = value
			operand.value = value
		else:
			operand.type = 'literal'
			try:
				operand.value = float(value)
			except:
				## use it as string:
				operand.value = value
	
	#def on__command(self, event):


def execute_condition_dialog(condition):
	dlg = ConditionDialog(None, condition)
	result = dlg.showModal()
	if result.accepted:
		result.condition = dlg.process()
	else : result.condition = None
	dlg.destroy()
	return result


if __name__ == '__main__':
	class TesT(model.Background):
		pass
	
	app = model.Application(TesT, r'minimal_app.rsrc.py')
	from Brain.condition import Condition
	ret = execute_condition_dialog(Condition())
	print ret.condition









